<?php

namespace App\Http\Middleware;

use Closure;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Facades\JWTAuth;
class GetUserFromToken
{
    /***
     *
     * @param $request
     * @param Closure $next
     * @return \Illuminate\Http\JsonResponse|mixed
     */
    public function handle($request, Closure $next)
    {
        try {
            if (! $user = JWTAuth::parseToken()->authenticate()) {
                return response()->json([
                    'errCode' => 400004,
                    'errMsg' => 'user not found'
                ], 404);
            }
        } catch (TokenExpiredException $e) {
            return response()->json([
                'errCode' => 400001,
                'errMsg' => 'token expired'
            ], 401);
        } catch (TokenInvalidException $e) {
            return response()->json([
                'errCode' => 400003,
                'errMsg' => 'token invalid'
            ], 403);
        } catch (JWTException $e) {
            return response()->json([
                'errCode' => 400002,
                'errMsg' => 'token absent'
            ], 402);
        }
        return $next($request);
    }
}
